package com.zhuhao.design_mode.behavioral_pattern.interator;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Iterator;
import java.util.NoSuchElementException;

// 实体类
@Getter
@AllArgsConstructor
class Book {
    private final String name;
}

// 具体集合类（书架）
class BookShelf implements Iterator<Book> {
    private final Book[] books;
    private int size = 0;
    private int index = 0;
    private final int capacity;

    public BookShelf(int capacity) {
        this.capacity = capacity;
        this.books = new Book[capacity];
    }

    public void addBook(Book book) {
        if (size >= capacity) {
            throw new IllegalStateException("书架已满");
        }
        books[size++] = book;
    }

    @Override
    public boolean hasNext() {
        return index < capacity;
    }

    @Override
    public Book next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return books[index++];
    }
}


// 客户端
public class SimpleIteratorDemo {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(3);
        bookShelf.addBook(new Book("Java编程思想"));
        bookShelf.addBook(new Book("设计模式"));
        bookShelf.addBook(new Book("重构"));

        while (bookShelf.hasNext()) {
            System.out.println(bookShelf.next().getName());
        }

    }
}